file-loader
作用:
处理资源文件的引入,如图片、字体等。
API:https://github.com/webpack-contrib/file-loader
安装:
npm install file-loader --save-dev
使用:
对于img
或css
中引入本地资源文件,那么在打包过程中就需要对这些资源路径做处理,这个时候就用到了file-loader:
//webpack.config.js
entry:"./src/index.js",
output:{
filename:"bundle.js",
path:"./dist"
},
module:{
rules:[
{
test:/\.css$/,
exclude:/node_modules/,
loader:['style-loader','css-loader']
},
{
test:/\.jpg/,
exclude:/node_modules/,
use:[
{
loader:'file-loader',
options:{}
}
]
}
]
}
如果不配置其它参数,这样打包后的文件名是该文件的内容hash,扩展名就是原扩展名,文件路径为output输出路径。
参数配置:
可以通过配置options来修改默认行为:
name:文件名及路径
{
test:/\.jpg/,
exclude:/node_modules/,
use:[
{
loader:'file-loader',
options:{
name:"[path][name].[ext]",//自定义文件名。这里了保留原始路径、原始名字、原始扩展名
}
}
]
}
名称 | 类型 | 默认值 | 描述 |
---|---|---|---|
[name] | string | file.basename | 文件名 |
[path] | string | file.dirname | 文件路径,相对于context |
[hash] | string | md5 | 内容hash值 |
[ext] | string | file.ext | 文件扩展名 |
由于文件名不可以包含/
,所以在name添加该字符串相当于对应的文件夹。
其中[hash]也可以配置:[<hashType>:hash:<digestType>:<length>]
名称 | 默认值 | 可选 |
---|---|---|
hashType | md5 | sha1、md5、sha256、sha512 |
digestType | base64 | hex、base26、base32、base49、base52、base58、base62、base64 |
length | 8 | 长度 |
所以[hash]等价于[md5:hash:base64:8],不过一般也不用。
context
默认应该是"",但我不知道用来干嘛的。
publicPath
文件引用前缀路径,一般是用在CDN的:
{
test:/\.jpg/,
exclude:/node_modules/,
use:[
{
loader:'file-loader',
options:{
name:"[path][name].[ext]",
publicPath:"http://www.google.com/"
}
}
]
}
//那么引用路径就是:http://www.google.com/[path][name].[ext]
outputPath
文件输出路径
outputPath和name会拼接,如:
{
test:/\.jpg/,
exclude:/node_modules/,
use:[
{
loader:'file-loader',
options:{
name:"image/[name].[ext]",
outputPath:"src/"
}
}
]
}
//那么输出路径就是:src/image/[name].[ext]
useRelativePath:boolean
是否启用相对路径,默认false。如:
options:{
name:"image/[name].[ext]",
outputPath:"/src/"
}
//那么引用路径就是绝对路径,/src/image/[name].[ext]
//这样文件可能会找不到,所以需要配置该属性为true
options:{
name:"image/[name].[ext]",
outputPath:"/src/"
useRelativePath:true,
}
//引用路径就是相对对路径,src/image/[name].[ext]
emitFile:boolean
是否输出文件,默认true,当设为false将不会输出文件到指定目录
总结
属性不多,一般配置的更少,但该loader确实非常实用的,整理一下常用配置写法:
{
test:/\.jpg/,
exclude:/node_modules/,
use:[
{
loader:'file-loader',
options:{
name:"[name].[ext]",
context:"",
publicPath:"",//如果资源文件会上传cdn,那应该配置该参数
outputPath:"src/",//输出目录
useRelativePath:true,//或缺省
emitFile:true,//输出文件
}
}
]
}